﻿using AutoMapper;
using Easy.Common.Results;
using Easy.Services.Dtos;
using Easy.Services.Entities;
using Easy.Services.Interface;
using Microsoft.AspNetCore.Mvc;

namespace Easy.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CompanyController(IMapper _mapper, ICompanyService _companyService, IUserService _userService) : BaseController
    {
        readonly IMapper mapper = _mapper;

        readonly ICompanyService companyService = _companyService;

        readonly IUserService userService = _userService;


        [HttpPost]
        public APIResult Add(AddCompanyDTO dto)
        {
            APIResult result = new();
            dto.Name = dto.Name.Trim();
            var isExist = companyService.Exist(r => r.Name.Equals(dto.Name) || r.Code.Equals(dto.Code));
            if (isExist)
            {
                result.Message = "部门名称或编码已存在";
                return result;
            }
            Company company = mapper.Map<Company>(dto);
            company.SetModelBase(tokenModel: TokenModel, true);
            var user = userService.Get(u => u.Id.Equals(dto.ManagerId));
            company.ManagerName = user?.UserName ?? "admin";
            var id = companyService.Add(company);
            if (id > 0)
            {
                result.Success = true;
                result.Message = "添加成功";
            }
            else
            {
                result.Message = "添加失败";
            }
            return result;

        }


        [HttpPost]
        public APIResult Update(CompanyDTO dto)
        {
            Company model = mapper.Map<Company>(dto);
            model.SetModelBase(tokenModel: TokenModel);
            var user = userService.Get(u => u.Id.Equals(dto.ManagerId));
            model.ManagerName = user?.UserName ?? model.ManagerName;
            var result = companyService.Update(model);
            return result;

        }


        [HttpGet]
        public APIResult Get(long id)
        {
            var model = companyService.Get(c => c.Id == id);
            var data = mapper.Map<CompanyDTO>(model);
            APIResult result = new()
            {
                Data = data,
                Success = model != null
            };
            return result;
        }


        [HttpDelete]
        public APIResult Delete(long id)=> companyService.Delete(id: id, tokenModel: TokenModel);


        [HttpGet]
        public APIResult GetList()
        {
            APIResult result = new();
            var list = companyService.GetList();
            result.Data = list;
            result.Success = list.Count > 0;
            return result;
        }


    }
}
